package com.changcheng.explorer.service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnDismissListener;
import android.graphics.Color;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import com.changcheng.explorer.FileList;
import com.changcheng.explorer.R;
import com.changcheng.explorer.dialog.FSCreateFileDialog;
import com.changcheng.explorer.dialog.FSRenameDialog;
import com.changcheng.explorer.enums.ListStyle;
import com.changcheng.explorer.thread.OnThreadEnd;
import com.changcheng.explorer.utils.FSFileUtils;

/**
 * @author Administrator
 * 
 */
public class FileListService {

	private static final String TAG = "FileListService";
	// 程序配置
	private static Properties set = null;
	// 主Activity
	private FileList fileList;
	// 显示文件列表
	private GridView gridView;
	// 选择文件导航记录
	private List<String> recorder;
	// 当前游标所在位置(recorder)
	private int current;
	// 视图类型
	private ListStyle listStyle = ListStyle.LIST;
	// 可以选择
	private boolean canSelect;
	// 被选中的文件
	private Set<Integer> selected = new HashSet<Integer>();

	static {
		InputStream in = FileListService.class.getClassLoader()
				.getResourceAsStream("set.properties");
		set = new Properties();
		try {
			set.load(in);
		} catch (IOException e) {
			Log.e(TAG, e.toString());
			e.printStackTrace();
		}
	}

	/**
	 * 构造方法
	 * 
	 * @param fileList
	 * @param gridView
	 */
	public FileListService(FileList fileList, GridView gridView) {
		this.fileList = fileList;
		this.gridView = gridView;
		this.recorder = new ArrayList<String>();
		this.current = 0;
		if (set.getProperty("listStyle").equals(ListStyle.TITLE.toString()))
			this.listStyle = ListStyle.TITLE;
		else
			this.listStyle = ListStyle.LIST;
	}

	/**
	 * 析构方法
	 */
	@Override
	protected void finalize() throws Throwable {
		super.finalize();
		FileOutputStream out = this.fileList.openFileOutput(
				"set.properties", Context.MODE_PRIVATE);
		set.save(out, "");
	}

	public Set<Integer> getSelected() {
		return selected;
	}

	public void setSelected(Set<Integer> selected) {
		this.selected = selected;
	}

	public boolean isCanSelect() {
		return canSelect;
	}

	public void setCanSelect(boolean canSelect) {
		this.canSelect = canSelect;
		if (!canSelect) {
			for (Integer position : this.selected) {
				Log.i(TAG, position.toString());
				View item = this.gridView.getChildAt(position);
				item.setBackgroundColor(Color.TRANSPARENT);
			}
		} else {
			this.selected.clear();
		}
	}

	public ListStyle getListStyle() {
		return listStyle;
	}

	public void setListStyle(ListStyle listStyle) {
		this.listStyle = listStyle;
		set.setProperty("listStyle", listStyle.toString());
		this.refresh();
	}

	public GridView getGridView() {
		return gridView;
	}

	public void setGridView(GridView gridView) {
		this.gridView = gridView;
	}

	public FileList getMainActivity() {
		return fileList;
	}

	public void setMainActivity(FileList fileList) {
		this.fileList = fileList;
	}

	/**
	 * 到根目录
	 */
	public void home() {
		String rootPath = set.getProperty("rootPath");
		fileList.setSelectState(false);
		fill(rootPath);
		change(rootPath);
	}

	/**
	 * 到指定的目录
	 */
	public void go(String path) {
		File file = new File(path);
		if (file == null || !file.exists())
			return;
		fileList.setSelectState(false);
		if (file.isFile())
			this.open(path);
		else
			this.fill(path);
	}

	/**
	 * 返回到上一层目录
	 */
	public void up() {
		if (recorder.size() <= 0 || current < 0 || current >= recorder.size())
			return;

		File file = new File(recorder.get(current));
		File parent = file.getParentFile();
		if (parent == null) {
			return;
		}
		fileList.setSelectState(false);
		fill(parent.getPath());
		change(parent.getPath());
	}

	/**
	 * 回退到当前位置的上一个位置
	 */
	public void back() {
		this.current--;
		if (recorder.size() <= 0 || this.current < 0) {
			this.current = 0;
			return;
		}

		if (this.current >= recorder.size()) {
			this.current = recorder.size() - 1;
			return;
		}
		fileList.setSelectState(false);
		this.refresh();
	}

	/**
	 * 前进到当前位置的下一个位置
	 */
	public void forward() {
		this.current++;
		if (this.current >= recorder.size()) {
			this.current = recorder.size() - 1;
			return;
		} else if (recorder.size() <= 0) {
			this.current = 0;
			return;
		}
		fileList.setSelectState(false);
		this.refresh();
	}

	/**
	 * 当前位置被改变
	 */
	public void change(String filePath) {
		recorder.add(filePath);
		this.current = recorder.size() - 1;
	}

	/**
	 * 获取当前目录位置
	 * 
	 * @return
	 */
	public String getCurrentPosition() {
		if (this.recorder == null || this.current < 0
				|| this.current >= this.recorder.size())
			return set.getProperty("rootPath");
		return this.recorder.get(this.current);
	}

	/**
	 * 打开文件
	 */
	public void open(String filePath) {
		File file = new File(filePath);
		if(file == null || !file.exists())
			throw new RuntimeException("file not found!");
		
		Intent intent = new Intent();  
		intent.setAction(android.content.Intent.ACTION_VIEW);
		Uri uri = Uri.fromFile(file);
		intent.setDataAndType(uri, FSFileUtils.getFileType(file.getPath()));
		this.fileList.startActivity(intent); 
	}

	public void refresh() {
		fill(this.recorder.get(this.current));
	}

	/**
	 * 获取指定目录的所有文件列表
	 * 
	 * @param files
	 */
	public void fill(String path) {
		List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
		// 目录/文件列表
		File dir = new File(path);
		if (dir == null || !dir.exists())
			return;
		//
		this.fileList.setTitle(path);
		File[] files = dir.listFiles();
		for (File file : files) {
			HashMap<String, Object> item = new HashMap<String, Object>();
			// 图标
			if (file.isFile()){
				item.put("image", FSFileUtils.getIco(file.getPath()));
				//item.put("image", R.drawable.file);
			}
			else if (file.isDirectory())
				item.put("image", R.drawable.folder);
			else
				item.put("image", R.drawable.file);
			// 文件
			item.put("file", file.getName());
			if (this.listStyle == ListStyle.LIST) {
				// 尺寸
				try {
					if (file.isFile())
						item.put("size", FSFileUtils.getSize(file.getPath()));
					else
						item.put("size", "");
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			}

			data.add(item);
		}
		// ******************* 显示 ********************
		// 创建Adapter
		ListAdapter adapter = null;
		// 列表视图显示方式
		if (this.listStyle == ListStyle.LIST) {
			adapter = new SimpleAdapter(fileList, data,
					R.layout.file_grid_list, new String[] { "image", "file",
							"size" }, new int[] { R.id.dirl_list_iv_img,
							R.id.dirl_list_tv_text, R.id.dirl_list_tv_size });
			gridView.setNumColumns(GridView.NO_STRETCH);
		} else if (this.listStyle == ListStyle.TITLE) {
			// 平铺显示方式
			adapter = new SimpleAdapter(
					fileList,
					data,
					R.layout.file_grid_title,
					new String[] { "image", "file" },
					new int[] { R.id.dirl_title_iv_img, R.id.dirl_title_tv_text });
			gridView.setNumColumns(GridView.AUTO_FIT);
		}
		// 设置gridView的Adapter
		gridView.setAdapter(adapter);
	}

	// ***************************************************************
	// ***************************** 编辑 *****************************
	// ***************************************************************
	/**
	 * 获取所有选中的文件完整路径
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private Set<String> getSelectedFiles() {
		Set<String> files = new HashSet<String>();
		for (Integer itemPos : this.selected) {
			HashMap<String, Object> item = (HashMap<String, Object>) this.gridView
					.getItemAtPosition(itemPos);
			files.add(this.recorder.get(this.current) + "/" + item.get("file"));
		}
		return files;
	}

	/**
	 * 创建目录
	 * 
	 * @throws Exception
	 */
	public void mkDir() throws Exception {

		// 创建对话框
		final FSCreateFileDialog cfDialog = new FSCreateFileDialog(
				getMainActivity(), getMainActivity().getString(
						R.string.dialog_createdir_title));
		cfDialog.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss(DialogInterface dialog) {
				try {
					String path = FileListService.this.recorder
							.get(FileListService.this.current);
					File file = new File(path + "/" + cfDialog.getName());
					if (file == null || file.exists())
						throw new Exception("file is exists!");
					//
					file.mkdir();
					fill(path);
				} catch (Exception e) {
					Log.e(TAG, e.toString());
					e.printStackTrace();
				}
			}
		});
		// 显示对话框
		cfDialog.show();
	}

	/**
	 * 重命名
	 */
	public void rename() {
		final FSRenameDialog fsrDialog = new FSRenameDialog(this.fileList,
				this.fileList.getString(R.string.dialog_reanme_title));
		fsrDialog.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss(DialogInterface dialog) {
				FSFileUtils.rename(getSelectedFiles(), fsrDialog.getNewName());
			}
		});
		fsrDialog.show();
		this.refresh();
	}

	/**
	 * 剪切
	 */
	public void cut() {
		FSFileUtils.cut(getSelectedFiles());
	}

	/**
	 * 复制
	 * 
	 * @throws FileNotFoundException
	 */
	public void copy() throws FileNotFoundException {
		FSFileUtils.copy(getSelectedFiles());
	}

	/**
	 * 粘贴
	 * 
	 * @throws IOException
	 */
	public void paste() throws IOException {
		String currentPosition = this.recorder.get(this.current);
		FSFileUtils.paste(this.fileList, currentPosition,
				new OnThreadEnd() {
					@Override
					public void doSomething() {
						refresh();
						selected.clear();
					}
				});
	}

	/**
	 * 删除
	 * 
	 * @throws IOException
	 */
	public void delete() {
		// 询问是否删除对话框
		AlertDialog.Builder builder = new AlertDialog.Builder(this.fileList);
		builder.setMessage(
				this.fileList.getString(R.string.edit_delete_alert))
				.setCancelable(true).setPositiveButton(
						this.fileList.getString(R.string.bt_ok),
						new DialogInterface.OnClickListener() {
							// 确认
							public void onClick(DialogInterface dialog, int id) {
								dialog.dismiss();
								try {
									// 删除
									FSFileUtils.delete(
											FileListService.this.fileList,
											getSelectedFiles(),
											new OnThreadEnd() {
												@Override
												public void doSomething() {
													// 刷新目录
													refresh();
													FileListService.this.selected
															.clear();
												}
											});
								} catch (IOException e) {
									Log.e(TAG, e.toString());
									e.printStackTrace();
								}
							}
						}).setNegativeButton(
						this.fileList.getString(R.string.bt_cancel),
						new DialogInterface.OnClickListener() {
							// 取消
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
		AlertDialog alert = builder.create();
		alert.show();
	}

}
